package com.kernowbunney;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;


public class SiteListFragment extends ListFragment {
	
	private boolean mDualPane;
	int mCurPos = 0;
	
	@Override
	public void onActivityCreated(Bundle savedInstance) {
		super.onActivityCreated(savedInstance);
		// set list adaptor
		ArrayAdapter<CharSequence> sitesAdapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.site_list, android.R.layout.simple_list_item_1);
		setListAdapter(sitesAdapter);
		
		/*
		this.getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				Toast.makeText(parent.getContext(), "Item clicked" + pos, Toast.LENGTH_LONG).show();
			}	
		});*/
		
		// check if the spec pane is visible:
		View specpane = getActivity().findViewById(R.id.spec_view_fragment);
		mDualPane = specpane != null && specpane.getVisibility() == View.VISIBLE;
	
		if(savedInstance != null) {
			// restore last checked position:
			mCurPos = savedInstance.getInt("curChoice", 0);
		}
		
		if(mDualPane) {
			getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			showSpec(mCurPos);
		}
	}
	

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showSpec(position);
    }
    
    void showSpec(int position) {
    	// see: http://developer.android.com/guide/components/fragments.html#Adding
    	
    	mCurPos = position;
    	
    	if(mDualPane) {
    		getListView().setItemChecked(position, true);
    		
    		// 	if in dual pane mode, get spec view and update with id:
    		SpecViewFragment specview = (SpecViewFragment)
    				getFragmentManager().findFragmentById(R.id.spec_view_fragment);
    		specview.setSite(this.getListView().getItemAtPosition(position).toString());
    		
    	}
    }
	
}
